package io.coderyeah.org.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.coderyeah.basic.annotation.LogAnnotation;
import io.coderyeah.basic.Result;
import io.coderyeah.org.domain.OperationLog;
import io.coderyeah.org.dto.OperationLogDTO;
import io.coderyeah.org.service.OperationLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;

@Api("日志记录管理类")
@RequestMapping("/log")
@RestController
public class OperationLogController {
    @Autowired
    private OperationLogService logService;

    @ApiOperation("获取所有操作日志")
    @PostMapping("/list")
    public Result getAll(@RequestBody OperationLogDTO logDTO) {
        final Page<OperationLog> page = new Page<>(logDTO.getCurrentPage(), logDTO.getPageSize());
        final LambdaQueryWrapper<OperationLog> wrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(logDTO.getUsername())) {
            wrapper.like(OperationLog::getUsername, logDTO.getUsername());
        }
        if (StrUtil.isNotBlank(logDTO.getMethodName())) {
            wrapper.like(OperationLog::getMethodName, logDTO.getMethodName());
        }
        if (StrUtil.isNotBlank(logDTO.getModule())) {
            wrapper.like(OperationLog::getModule, logDTO.getModule());
        }
        if (StrUtil.isNotBlank(logDTO.getIp())) {
            wrapper.like(OperationLog::getIp, logDTO.getIp());
        }
        final Page<OperationLog> logPage = logService.page(page, wrapper);
        return Result.success(logPage.getRecords(), logPage.getTotal());
    }

    @LogAnnotation(module = "日志模块", operate = "添加/修改日志")
    @ApiOperation("添加/修改日志")
    @PostMapping("/saveOrUpdate")
    public Result saveOrUpdate(@RequestBody OperationLogDTO logDTO) {
        return logService.saveOrUpdate(logDTO);
    }

    @ApiOperation("批量删除日志")
    @PatchMapping("/delByBatch")
    public Result delByBatch(@RequestBody OperationLogDTO logDTO) {
        System.out.println(Arrays.toString(logDTO.getIds()));
        logService.removeByIds(Arrays.asList(logDTO.getIds()));
        return Result.success("批量删除成功");
    }

    @ApiOperation("删除日志")
    @DeleteMapping("/del/{id}")
    public Result deleteById(@PathVariable("id") Long id) {
        try {
            logService.removeById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(e.getMessage());
        }
        return Result.success("删除成功");
    }

}
